<template>
  <div style="padding: 20px;">
  <h1 style="margin: 20px">服务记录表信息管理</h1>
<!--  <div class="operation_panel">
    <el-button type="primary" :icon="Plus" @click="showAddDialog">添加新数据</el-button>
    <el-button type="danger" :icon="Delete" @click="handleDeleteSelectionRows">删除选中行数据</el-button>
    &lt;!&ndash; 添加搜索框 &ndash;&gt;
    <el-input
        v-model="searchQuery"
        placeholder="请输入服务记录ID进行搜索"
        clearable
        style="width: 300px; margin-left: 16px"
        @input="handleSearch"
    >
      <template #prefix>
        <el-icon><search /></el-icon>
      </template>
    </el-input>
  </div>-->
  <!-- 表头 -->
  <el-table
      :data="tableData.slice((currentPage - 1) * pageSize, currentPage * pageSize)"
      style="width: 100%"
      border
      ref="multipleTableRef"
  >
    <el-table-column fixed type="index" label="序号" width="60" />
    <el-table-column fixed type="selection" width="60" />
    <el-table-column fixed prop="serviceRecordId" label="服务记录ID" width="60" />
    <el-table-column prop="appointmentId" label="预约ID" width="60" />
    <el-table-column prop="patientId" label="患者ID" width="60" />
    <el-table-column prop="patient_name" label="患者姓名" width="80" />
    <el-table-column prop="escortId" label="陪诊人员ID" width="60" />
    <el-table-column prop="escort_name" label="陪诊人员姓名" width="80" />
    <el-table-column
        prop="serviceStartTime"
        label="服务开始时间"
        width="180"
        :formatter="formatDate"
    />
    <el-table-column
        prop="serviceEndTime"
        label="服务结束时间"
        width="180"
        :formatter="formatDate"
    />
    <el-table-column prop="serviceContent" label="服务内容描述" />
    <el-table-column prop="serviceEvaluation" label="服务评价" width="200" />
    <el-table-column prop="serviceFee" label="服务费用" width="120" />
<!--    <el-table-column fixed="right" label="操作" width="150">
      <template #default="scope">
        <el-button
            size="small"
            type="primary"
            @click="showEditDialog(scope.$index, scope.row)"
        >
          Edit
        </el-button>
        <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
        >
          Delete
        </el-button>
      </template>
    </el-table-column>-->
  </el-table>
  <!-- 表尾 -->
  <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[20, 40, 60, 80, 100]"
      background
      layout="prev, pager, next, jumper, total, sizes"
      :total="tableData.length"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
  />
  <!-- 添加新数据对话框 -->
  <el-dialog v-model="dialogFormVisible" title="服务记录管理" width="500">
    <!-- 添加 :rules 属性和 ref 用于表单验证 -->
    <el-form :model="form" :rules="rules" ref="formRef" label-position="right" label-width="auto">
      <el-form-item label="预约ID" prop="appointmentId">
        <el-input v-model="form.appointmentId" autocomplete="off" placeholder="请输入预约ID" />
      </el-form-item>
      <el-form-item label="患者ID" prop="patientId">
        <el-input v-model="form.patientId" autocomplete="off" placeholder="请输入患者ID" />
      </el-form-item>
      <el-form-item label="陪诊人员ID" prop="escortId">
        <el-input v-model="form.escortId" autocomplete="off" placeholder="请输入陪诊人员ID" />
      </el-form-item>
      <el-form-item label="服务开始时间" prop="serviceStartTime">
        <el-date-picker
            v-model="form.serviceStartTime"
            type="datetime"
            placeholder="选择服务开始时间"
            value-format=""
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="服务结束时间" prop="serviceEndTime">
        <el-date-picker
            v-model="form.serviceEndTime"
            type="datetime"
            placeholder="选择服务结束时间"
            value-format=""
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="服务内容描述" prop="serviceContent">
        <el-input
            v-model="form.serviceContent"
            autocomplete="off"
            placeholder="请输入服务内容描述"
            type="textarea"
        />
      </el-form-item>
      <el-form-item label="服务评价" prop="serviceEvaluation">
        <el-input v-model="form.serviceEvaluation" autocomplete="off" placeholder="请输入服务评价" />
      </el-form-item>
      <el-form-item label="服务费用" prop="serviceFee">
        <el-input v-model.number="form.serviceFee" autocomplete="off" placeholder="请输入服务费用" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="!isEdit" type="primary" @click="handleAdd">新增</el-button>
        <el-button v-else type="primary" @click="handleEdit">修改</el-button>
      </div>
    </template>
  </el-dialog></div>
</template>

<script>
import { Delete, Plus } from "@element-plus/icons-vue";
import axios from "axios";
import { ElMessage } from "element-plus";
import {mapGetters} from "vuex";

export default {
  computed: {
    ...mapGetters(['getUserId']) // 假设 Vuex 中存储的是
  },
  components: { Delete, Plus },
  data() {
    return {
      currentPage: 1,
      pageSize: 20,
      dialogFormVisible: false,
      isEdit: false,
      tableData: [], // 表格数据
      searchQuery: "", // 搜索框内容
      form: {
        serviceRecordId: null,
        appointmentId: null,
        patientId: null,
        escortId: null,
        serviceStartTime: null,
        serviceEndTime: null,
        serviceContent: "",
        serviceEvaluation: "",
        serviceFee: null,
        patient_name: "",
        escort_name: ""
      },
      // 定义表单验证规则
      rules: {
        appointmentId: [
          { required: true, message: '请输入预约ID', trigger: 'blur' }
        ],
        patientId: [
          { required: true, message: '请输入患者ID', trigger: 'blur' }
        ],
        escortId: [
          { required: true, message: '请输入陪诊人员ID', trigger: 'blur' }
        ],
        serviceStartTime: [
          { required: true, message: '请选择服务开始时间', trigger: 'change' }
        ],
        serviceEndTime: [
          { required: true, message: '请选择服务结束时间', trigger: 'change' }
        ],
        serviceContent: [
          { required: true, message: '请输入服务内容描述', trigger: 'blur' }
        ],
        serviceEvaluation: [
          { required: true, message: '请输入服务评价', trigger: 'blur' }
        ],
        serviceFee: [
          { required: true, message: '请输入服务费用', trigger: 'blur' },
          { type: 'number', message: '服务费用必须为数字', trigger: 'blur' }
        ]
      }
    };
  },
  created() {
    this.getTableData();
  },
  methods: {
    // 处理搜索
    async handleSearch() {
      if (this.searchQuery.trim() === "") {
        this.getTableData(); // 如果搜索框为空，重新加载所有数据
        return;
      }
      try {
        const res = await axios.get(`/api/wu_vue_2_test/ServiceRecord/SelectByName?name=${this.searchQuery}`);
        if (res.data.data.length === 0) {
          ElMessage({
            message: "未查询到该名字",
            type: "warning",
            plain: true,
          });
        }
        this.tableData = res.data.data; // 更新表格数据
      } catch (error) {
        console.error("搜索失败:", error);
        ElMessage({
          message: "ID="+this.searchQuery+",搜索失败，请稍后重试",
          type: "error",
          plain: true,
        });
      }
    },
    // 日期格式化函数
    formatDate(row, column, cellValue) {
      if (cellValue) {
        const date = new Date(cellValue);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, "0");
        const day = String(date.getDate()).padStart(2, "0");
        const hours = String(date.getHours()).padStart(2, "0");
        const minutes = String(date.getMinutes()).padStart(2, "0");
        const seconds = String(date.getSeconds()).padStart(2, "0");
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      }
      return "";
    },
    // 1. 获取所有数据
    async getTableData() {
      try {
        const UserId = this.getUserId;
        const res = await axios.get(`/api/wu_vue_2_test/ServiceRecord/getByUserid?UserId=${UserId}`);
        console.log(res.data);
        this.tableData = res.data.data;
      } catch (error) {
        console.error("获取数据失败:", error);
        ElMessage({
          message: "获取数据失败，请稍后重试",
          type: "error",
          plain: true
        });
      }
    },
    // 2. 添加新数据
    async handleAdd() {
      // 触发表单验证
      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          try {
            console.log(this.form);
            const {patient_name, escort_name, ...rest} = this.form;
            const res = await axios.post(
                "/api/wu_vue_2_test/ServiceRecord/add",
                rest
            );
            console.log(res);
            this.dialogFormVisible = false;
            await this.getTableData();
            this.showMsg(res);
          } catch (error) {
            console.error("添加数据失败,被占用或网络不佳:", error);
            ElMessage({
              message: "添加数据失败,被占用或网络不佳，请稍后重试",
              type: "error",
              plain: true
            });
          }
        } else {
          console.log('表单验证不通过');
          return false;
        }
      });
    },
    // 3. 删除当前行数据
    async handleDelete(index, row) {
      try {
        const {patient_name, escort_name, ...rest} = row;
        const res = await axios.post(
            "/api/wu_vue_2_test/ServiceRecord/del",
            rest
        );
        await this.getTableData();
        this.showMsg(res);
      } catch (error) {
        console.error("删除数据失败:", error);
        ElMessage({
          message: "删除数据失败，请稍后重试",
          type: "error",
          plain: true
        });
      }
    },
    // 4. 修改当前行数据
    async handleEdit() {
      // 触发表单验证
      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          try {
            const {patient_name, escort_name, ...rest} = this.form;
            const res = await axios.post(
                "/api/wu_vue_2_test/ServiceRecord/update",
                rest
            );
            this.dialogFormVisible = false;
            await this.getTableData();
            this.showMsg(res);
          } catch (error) {
            console.error("修改数据失败,被占用或网络不佳:", error);
            ElMessage({
              message: "修改数据失败,被占用或网络不佳，请稍后重试",
              type: "error",
              plain: true
            });
          }
        } else {
          console.log('表单验证不通过');
          return false;
        }
      });
    },
    // 5. 删除选中行数据
    async handleDeleteList(selectedRows) {
      try {
        const filteredRows = selectedRows.map(({patient_name, escort_name, ...rest}) => rest);
        const res = await axios.post(
            "/api/wu_vue_2_test/ServiceRecord/delList",
            filteredRows
        );
        await this.getTableData();
        this.showMsg(res);
      } catch (error) {
        console.error("批量删除数据失败:", error);
        ElMessage({
          message: "批量删除数据失败，请稍后重试",
          type: "error",
          plain: true
        });
      }
    },
    // 删除选中行数据（批量删除）
    handleDeleteSelectionRows() {
      const selectedRows = this.$refs.multipleTableRef.getSelectionRows();
      console.log(selectedRows);
      this.handleDeleteList(selectedRows);
    },
    // 分页事件处理方法
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      console.log("handleSizeChange", this.pageSize);
    },
    // 分页事件处理方法
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      console.log("handleCurrentChange", this.currentPage);
    },
    // 显示添加新数据对话框
    showAddDialog() {
      this.isEdit = false;
      this.dialogFormVisible = true;
      this.resetForm();
    },
    // 显示编辑对话框
    showEditDialog(index, row) {
      console.log(index, row);
      this.dialogFormVisible = true;
      this.isEdit = true;
      this.form = {...row};
    },
    // 重置表单
    resetForm() {
      this.form = {
        serviceRecordId: null,
        appointmentId: null,
        patientId: null,
        escortId: null,
        serviceStartTime: null,
        serviceEndTime: null,
        serviceContent: "",
        serviceEvaluation: "",
        serviceFee: null,
        patient_name: "",
        escort_name: ""
      };
    },
    // 显示操作结果消息
    showMsg(res) {
      if (res.data.code === 200) {
        ElMessage({
          message: res.data.msg,
          type: "success",
          plain: true
        });
      } else {
        ElMessage({
          message: res.data.msg,
          type: "error",
          plain: true
        });
      }
    }
  }
};
</script>

<style scoped>
h1 {
  color: #191919;
}

.operation_panel {
  margin-bottom: 16px;
}

.el-pagination {
  margin-top: 16px;
}
</style>